package com.example.demo.service.impl;

import com.example.demo.mapper.UserMapper;
import com.example.demo.model.entity.user.User;
import com.example.demo.model.enums.UserTypeEnum;
import com.example.demo.security.AdminPrincipal;
import com.example.demo.security.StudentPrincipal;
import com.example.demo.security.TeacherPrincipal;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@RequiredArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService {

    private final UserMapper userMapper;

    @Override
    @Transactional
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userMapper.findByUsername(username)
                .orElseThrow(() -> new UsernameNotFoundException("用户不存在: " + username));

        if (user.getUserType() == UserTypeEnum.TEACHER) {
            return TeacherPrincipal.create(user);
        } else if (user.getUserType() == UserTypeEnum.STUDENT) {
            return StudentPrincipal.create(user);
        } else if (user.getUserType() == UserTypeEnum.ADMIN) {
            return AdminPrincipal.create(user);
        } else {
            throw new IllegalStateException("未知的用户类型: " + user.getUserType());
        }
    }
}